<template>
  <el-form ref="formRef" :inline="true" :model="info" :rules="rules" style="width: 600px;">
    <el-form-item prop="title" label="文件标题：" class="w-full ">
      <el-input v-model="info.title" clearable />
    </el-form-item>
    <el-form-item prop="remark" label="文件描述：" class="w-full ">
      <el-input v-model="info.remark" clearable type="textarea" :autosize="{ minRows: 5 }" />
    </el-form-item>
    <el-form-item label="文件：">
      <el-upload ref="uploadRef" class="upload-demo" action="/admin/documentInf/upload" :limit="1"
        :on-exceed="handleExceed" :on-change="handleChange" :auto-upload="false" :headers="uploadHeaders"
        v-model:file-list="uploadList">
        <template #trigger>
          <el-button type="primary">上传文件</el-button>
        </template>
      </el-upload>
    </el-form-item>
    <div>
      <el-button type="primary" @click="handleInfoChange(formRef)">
        提交
      </el-button>
    </div>
  </el-form>
</template>

<script lang="ts" setup>
import {  ApiPost } from '@/utils/Axios';
import { ElMessage, ElMessageBox, ElNotification, genFileId, UploadInstance, UploadProps, UploadRawFile, type FormInstance } from 'element-plus';
import { reactive, ref, watch } from 'vue'
const info = ref({
  title: "",
  remark: "",
  filename: null,
  username: null,
  token: null
})

const formRef = ref<FormInstance>()
const uploadRef = ref<UploadInstance>()
const uploadHeaders = {
  "Authorization": localStorage.getItem("token"),
}
const uploadList = ref([])

const validateFiletitle = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('文件标题不能为空'))
  } else {
    callback()
  }
}

const validateFileremark = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('文件描述不能为空'))
  } else {
    callback()
  }
}
const rules = reactive({
  title: [{ validator: validateFiletitle, trigger: 'blur' }],
  remark: [{ validator: validateFileremark, trigger: 'blur' }],
})


const handleInfoChange = (formEl: FormInstance | undefined) => {
  formEl.validate(vail => {
    if(!info.value.filename) {
      ElMessage({
        message: "请上传文件",
        type: "error",
        showClose: false,
        duration: 2000,
      })
    }
    if (vail&&info.value.filename) {
      ElMessageBox({
        title: "提醒",
        type: "warning",
        message: "确认新增吗？",
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        showCancelButton: true,
      }).then(() => {
        const { title, remark, filename } = info.value
        ApiPost("/documentInf/add", { title, remark, filename }).then(res => {
          console.log(res)
          if (res.code === 200) {
            ElNotification({
              title: "新增成功",
              type: "success",
              showClose: false,
              duration: 2000,
            })
          }
        })
      }).catch(() => {
        return
      })
    }
  })

}

const handleExceed: UploadProps['onExceed'] = (files) => {
  uploadRef.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = genFileId()
  uploadRef.value!.handleStart(file)
}

const handleChange: UploadProps['onChange'] = (file, fileList) => {
  switch (file.status) {
    case "ready":
      uploadRef.value!.submit()
      break;
    case "uploading":
      break;
    case "success":
      if (file.response["code"] === 200) {
        info.value.filename = file.response["data"].fileName
      }
      break;
    default:
      break;
  }
}
</script>

<style></style>